package Leetcode.lc347;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

public class Sloution {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        //开始统计
        for(int i=0;i<nums.length;i++){
            //merge函数，直接累加
            map.merge(nums[i],1,Integer::sum);
        }
        //开始堆排序
        PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(
                (a, b) -> a.getValue() - b.getValue()
        );
        Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
        for(Map.Entry<Integer, Integer> i:entries){
            if(queue.size()<k){
                queue.add(i);
            }else{
                if(queue.peek().getValue()<i.getValue()){
                    queue.poll();
                    queue.add(i);
                }
            }
        }
        int[] res=queue.stream().map(Map.Entry<Integer, Integer>::getKey).
                mapToInt(Integer::intValue).toArray();
        return res;
    }
}
